import Vue from 'vue'
import Vuex from 'vuex'

import _axios from 'axios'

let config = {
  baseURL: process.env.baseURL || process.env.apiUrl || '/api',
  timeout: 150 * 1000, // Timeout
  withCredentials: true // Check cross-site Access-Control
}

const axios = _axios.create(config)

axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
axios.interceptors.response.use(
  function({ data }) {
    var error
    if (data !== undefined && data.success !== undefined) {
      if (data.success == 1) {
        // 正确响应
        return data.data
      } else {
        // 一般错误
        error = data
      }
    } else {
      // 严重错误
      error = {
        success: 0,
        err_msg: '后端服务器未配置'
      }
    }
    return Promise.reject(error)
  },
  function(error) {
    return Promise.reject(error)
  }
)

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    imageUrl: '',
    resultInfo: null
  },
  mutations: {
    saveResultInfo(state, resultInfo) {
      state.resultInfo = resultInfo
    },
    saveImageUrl(state, imageUrl) {
      state.imageUrl = imageUrl
    }
  },
  getters: {
    resultInfo: s => s.resultInfo,
    imageUrl: s => s.imageUrl
  },
  actions: {
    async uploads(context, payload) {
      context.commit('saveImageUrl', payload.imageUrl)
    },
    async reset(context) {
      context.commit('saveResultInfo', null)
    },
    async classify(context, payload) {
      try {
        let data = await axios.post('classify', payload)
        context.commit('saveResultInfo', data)
      } catch {
        Vue.prototype.$message({
          message: '请求图片分析失败，请稍后再试！',
          type: 'warning'
        })
      }
    }
  }
})
